package com.cxh.mchat.bussiness.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cxh.mchat.bussiness.bean.MessageCountBean;
import com.cxh.mchat.bussiness.entity.Message;
import com.cxh.mchat.bussiness.mapper.MessageMapper;
import com.cxh.mchat.bussiness.service.IMessageService;
import com.cxh.mchat.common.constant.StatusConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cxh
 * @since 2021-12-30
 */
@Service
@Slf4j
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements IMessageService {
    /**
     * 保存聊天记录
     * @return 结果
     */
    @Override
    public boolean add(Message message) {

        //未读
        message.setStatus(StatusConstant.FALSE);
        boolean rtn = save(message);

        return rtn;
    }

    @Override
    public MessageCountBean queryNoReadCount(String userNo, String bussinessNo) {
        List<Message> messageList = getBaseMapper().selectList(new QueryWrapper<Message>()
                .eq("send_user_no", bussinessNo)
                .eq("received_user_no", userNo)
                .eq("status", StatusConstant.FALSE)
                .orderByDesc("create_time"));

        MessageCountBean messageCountBean = new MessageCountBean();
        messageCountBean.setNewMsgCount(0);
        if(!CollectionUtils.isEmpty(messageList)){
            messageCountBean.setNewMsgCount(messageList.size());
            messageCountBean.setNewMsgPreview(messageList.get(0).getText());
        }

        return messageCountBean;
    }
}
